package com.lingshu.app.base;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.lingshu.app.R;
import com.lingshu.app.config.ActivityStack;
import com.lingshu.app.config.LoadState;
import com.lingshu.app.databinding.ActivityBaseBinding;
import com.lingshu.app.databinding.ViewLoadErrorBinding;
import com.lingshu.app.databinding.ViewLoadingBinding;
import com.lingshu.app.databinding.ViewNoDataBinding;
import com.lingshu.app.databinding.ViewNoNetworkBinding;
import com.lingshu.app.ui.login.LoginActivity;

import cn.hutool.core.util.StrUtil;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2023/12/28 13:51
 * @Description
 */
public abstract class BaseActivity<DB extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity {
    protected AppCompatActivity context;
    protected DB dataBinding;
    protected VM viewModel;
    protected boolean isDialogShown = false; // 标志位

    private AlertDialog globalDialog;
    private ActivityBaseBinding activityBaseBinding;
    private ViewLoadingBinding viewLoadingBinding;
    private ViewLoadErrorBinding viewLoadErrorBinding;
    private ViewNoDataBinding viewNoDataBinding;
    private ViewNoNetworkBinding viewNoNetworkBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent(getIntent());

        if (isNoActionBar()) {
            setNoActionBar();
        }

        this.context = this;
        ActivityStack.getInstance().addActivity(this);
        activityBaseBinding = DataBindingUtil.setContentView(this, R.layout.activity_base);
        dataBinding = DataBindingUtil.inflate(getLayoutInflater(), getLayoutResId(), activityBaseBinding.flContentContainer, true);
        initViewModel();
        bindViewModel();
        dataBinding.setLifecycleOwner(this);
        initLoadState();
        init();
        // ViewModel订阅生命周期事件
        if (viewModel != null) {
            getLifecycle().addObserver(viewModel);
        }

        //统一的提示信息
        viewModel.infoMsg.observe(context, msg -> {
            alertDialogMessage(msg);
        });

        //统一的跳转
        viewModel.tokenIsValid.observe(context, result -> {
            if (!result) {
                jumpActivity(LoginActivity.class);
            }
        });
    }

    @Override
    protected synchronized void onDestroy() {
        super.onDestroy();
        ActivityStack.getInstance().removeActivity(this);
        if (dataBinding != null) {
            dataBinding.unbind();
        }
    }

    /**
     * 弹出信息
     *
     * @param message
     */
    public void alertDialogMessage(String message) {
        if (StrUtil.isNotBlank(message)) {
            if (!isDialogShown) {
                isDialogShown = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                View dialogView = getLayoutInflater().inflate(R.layout.custom_message_dialog, null);
                TextView textView = dialogView.findViewById(R.id.tv_global);
                textView.setText(message);
                dialogView.findViewById(R.id.img_global_close).setOnClickListener(v -> globalDialog.dismiss());
                builder.setView(dialogView);
                globalDialog = builder.create();
                globalDialog.setOnDismissListener(dialog -> {
                    isDialogShown = false;
                    viewModel.infoMsg.postValue(null);
                });
                globalDialog.setOnCancelListener(dialog -> {
                    isDialogShown = false;
                    viewModel.infoMsg.postValue(null);
                });
                globalDialog.show();
            }
        }
    }

    /**
     * 设置沉浸式状态栏
     */
    private void setNoActionBar() {
        Window window = getWindow();
        View decorView = window.getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private void initLoadState() {
        if (viewModel != null && isSupportLoad()) {
            viewModel.loadState.observe(this, loadState -> {
                switchLoadView(loadState);
            });
        }
    }

    private void removeLoadView() {
        int childCount = activityBaseBinding.flContentContainer.getChildCount();
        if (childCount > 1) {
            activityBaseBinding.flContentContainer.removeViews(1, childCount - 1);
        }
    }

    private void switchLoadView(LoadState loadState) {
        removeLoadView();
        switch (loadState) {
            case LOADING:
                if (viewLoadingBinding == null) {
                    viewLoadingBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_loading, activityBaseBinding.flContentContainer, false);
                }
                activityBaseBinding.flContentContainer.addView(viewLoadingBinding.getRoot());
                break;

            case NO_NETWORK:
                if (viewNoNetworkBinding == null) {
                    viewNoNetworkBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_no_network, activityBaseBinding.flContentContainer, false);
                    viewNoNetworkBinding.setViewModel(viewModel);
                }
                activityBaseBinding.flContentContainer.addView(viewNoNetworkBinding.getRoot());
                break;

            case NO_DATA:
                if (viewNoDataBinding == null) {
                    viewNoDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_no_data, activityBaseBinding.flContentContainer, false);
                }
                activityBaseBinding.flContentContainer.addView(viewNoDataBinding.getRoot());
                break;

            case ERROR:
                if (viewLoadErrorBinding == null) {
                    viewLoadErrorBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.view_load_error, activityBaseBinding.flContentContainer, false);
                }
                activityBaseBinding.flContentContainer.addView(viewLoadErrorBinding.getRoot());
                break;

            default:
                break;
        }
    }

    /**
     * 跳转页面
     *
     * @param clazz 目标页面
     */
    protected void jumpActivity(Class<?> clazz) {
        Intent intent = new Intent(context, clazz);
        startActivity(intent);
    }

    /**
     * 跳转页面并关闭当前页面
     *
     * @param clazz 目标页面
     */
    protected void jumpActivityFinish(Class<?> clazz) {
        Intent intent = new Intent(context, clazz);
        startActivity(intent);
        finish();
    }

    /**
     * 处理参数
     *
     * @param intent 参数容器
     */
    protected void handleIntent(Intent intent) {

    }

    /**
     * 是否为沉浸模式
     *
     * @return true表示支持，false表示不支持
     */
    protected boolean isNoActionBar() {
        return false;
    }

    /**
     * 是否支持页面加载。默认不支持
     *
     * @return true表示支持，false表示不支持
     */
    protected boolean isSupportLoad() {
        return true;
    }

    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化ViewModel
     */
    protected abstract void initViewModel();

    /**
     * 绑定ViewModel
     */
    protected abstract void bindViewModel();

    /**
     * 初始化
     */
    protected void init() {

    }
}
